package com.by_man.presenter.module_health_records.attention;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.main_page.MainActivity;
import com.by_man.presenter.module_gestureLock.GestureLockActivity;
import com.by_man.repository.PostJsonArrayRequest;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 特别关注
 * Created by man on 2017-02-24.
 */
public class AttentionContentActivity extends AppCompatActivity {
    private RequestQueue rQueue;
    private JSONArray reponse;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attention_content);
        //rQueue = Volley.newRequestQueue(this);
        rQueue = SharedApplication.getrQueue(getApplication());
        rQueue.start();
        //页面相关组件的初始化
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("position", 2);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }

    protected void onRestart()
    {
        super.onRestart();
        Intent intent=new Intent(this,GestureLockActivity.class);
        intent.putExtra("class",this.getClass().getName());
        intent.putExtra("position", 2);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        // 获取关注信息内容
        final ListView listView = (ListView) findViewById(R.id.list_view);
        // 存放信息
        final ArrayList<HashMap<String,String>> contents = new ArrayList<>();
        String url = getResources().getString(R.string.attention_contents);
        HashMap<String, String> params = new HashMap<>();
        params.put("token", UserInfos.token);
        JSONObject jsonObject = new JSONObject(params);
        PostJsonArrayRequest jsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST,
                url, jsonObject,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        reponse = jsonArray;
                        if(0 == jsonArray.length()) {
                            HashMap<String, String> info = new HashMap<String, String>();
                            info.put("name", "暂无数据上传");
                            info.put("time", "请你上传数据给你的医生，请他（她）帮你分析");
                            contents.add(info);
                            SimpleAdapter adapter = new SimpleAdapter(AttentionContentActivity.this,
                                    contents, R.layout.attention_content_listview_item,
                                    new String[]{"name", "time"}, new int[]{R.id.name, R.id.time});
                            listView.setAdapter(adapter);
                        } else {
                            try {
                                JSONObject temp, temp2;
                                String str1, str2;
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    temp = (JSONObject) jsonArray.get(j);
                                    str1 = temp.getString("ocr_report_id");
                                    if (j > 0) {
                                        temp2 = (JSONObject) jsonArray.get(j-1);
                                        str2 = temp2.getString("ocr_report_id");
                                        if (!str1.equals(str2)) {
                                            HashMap<String, String> map = new HashMap<String, String>();
                                            map.put("name", temp.getString("report_name"));
                                            map.put("time", temp.getString("create_at").substring(0,10));
                                            map.put("ocr_report_id", str1);
                                            contents.add(map);
                                        }
                                    } else {
                                        HashMap<String, String> map = new HashMap<String, String>();
                                        map.put("name", temp.getString("report_name"));
                                        map.put("time", temp.getString("create_at").substring(0,10));
                                        map.put("ocr_report_id", str1);
                                        contents.add(map);
                                    }
                                }
                                SimpleAdapter adapter = new SimpleAdapter(AttentionContentActivity.this, contents, R.layout.attention_content_listview_item,
                                        new String[]{"name", "time"}, new int[]{R.id.name, R.id.time});
                                listView.setAdapter(adapter);
                            }catch (JSONException je) {
                                je.printStackTrace();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("AttentionContentError",volleyError.getMessage(),volleyError);
                    }
                });

        rQueue.add(jsonArrayRequest);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String ocrid = contents.get(i).get("ocr_report_id");
                try {
                    JSONObject temp;
                    JSONArray infos = new JSONArray();
                    if (null != reponse) {
                        for (int j = 0; j < reponse.length(); j++) {
                            temp = (JSONObject) reponse.get(j);
                            if (ocrid.equals(temp.getString("ocr_report_id"))) {
                                infos.put(temp);
                            }
                        }
                        Intent intent = new Intent(AttentionContentActivity.this, DetailContentActivity.class);
                        intent.putExtra("jsonString", infos.toString());
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                } catch (JSONException je) {
                    je.printStackTrace();
                }
            }
        });
    }
}
